package org.bjou

import org.springframework.dao.DataIntegrityViolationException

class CourseRuleController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
         def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        
          if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
         println "currentTerm:"+ params.currentTerm
         if (params.currentTerm==null) params.currentTerm = currentTerm
        println "currentTerm:"+ params.currentTerm 
       
          
        def cel = {  
            if(params.currentTerm){  
                 eq("currentTerm", params.currentTerm)
            }
            if(params.ruleType){  
                like("ruleType", "%${params.ruleType}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            if(params.majorName){  
                like("majorName", "%${params.majorName}%")  
            }
            if(params.ruleCode){  
                like("ruleCode", "%${params.ruleCode}%")  
            }
            if(params.ruleSet){  
                 like("ruleSet", "%${params.ruleSet}%")  
            }
            if(params.ruleYear){  
                eq("ruleYear", params.ruleYear)
            }
            if(params.ruleSeason){  
                eq("ruleSeason", params.ruleSeason)
            }
            
          }  
          
       
        
        def courseRuleList = CourseRule.createCriteria().list(params,cel) 
        [courseRuleInstanceList: courseRuleList, courseRuleInstanceTotal: courseRuleList.totalCount]
//        params.max = Math.min(params.max ? params.int('max') : 10, 100)
//        [courseRuleInstanceList: CourseRule.list(params), courseRuleInstanceTotal: CourseRule.count()]
    }

    def create() {
        [courseRuleInstance: new CourseRule(params)]
    }

    def save() {
        println params
        def courseRuleInstance = new CourseRule(params)
        if (!courseRuleInstance.save(flush: true)) {
            render(view: "create", model: [courseRuleInstance: courseRuleInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), courseRuleInstance.id])
        redirect(action: "show", id: courseRuleInstance.id)
    }

    def show() {
        def courseRuleInstance = CourseRule.get(params.id)
        if (!courseRuleInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), params.id])
            redirect(action: "list")
            return
        }

        [courseRuleInstance: courseRuleInstance]
    }

    def edit() {
        def courseRuleInstance = CourseRule.get(params.id)
        if (!courseRuleInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), params.id])
            redirect(action: "list")
            return
        }

        [courseRuleInstance: courseRuleInstance]
    }

    def update() {
        def courseRuleInstance = CourseRule.get(params.id)
        if (!courseRuleInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (courseRuleInstance.version > version) {
                courseRuleInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'courseRule.label', default: 'CourseRule')] as Object[],
                          "Another user has updated this CourseRule while you were editing")
                render(view: "edit", model: [courseRuleInstance: courseRuleInstance])
                return
            }
        }

        courseRuleInstance.properties = params

        if (!courseRuleInstance.save(flush: true)) {
            render(view: "edit", model: [courseRuleInstance: courseRuleInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), courseRuleInstance.id])
        redirect(action: "show", id: courseRuleInstance.id)
    }

    def delete() {
        def courseRuleInstance = CourseRule.get(params.id)
        if (!courseRuleInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), params.id])
            redirect(action: "list")
            return
        }

        try {
            courseRuleInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'courseRule.label', default: 'CourseRule'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
    
    
     def upload = { 
        params.entryTerm = Config.findByConfigKey('currentTerm')?.configValue
        render (view:'upload')
     }
     
    
    
    def uploadCourseRule = {
       def files = request.getFileMap();
       //handle uploaded file
        def uploadedFile = request.getFile('fileupload')
    
      if(!uploadedFile.empty){
      println "Class: ${uploadedFile.class}"
      println "Name: ${uploadedFile.name}"
      println "OriginalFileName: ${uploadedFile.originalFilename}"
      println "Size: ${uploadedFile.size}"
      println "ContentType: ${uploadedFile.contentType}"
      println "currentTerm: ${params.entryTerm}"

      def webRootDir = servletContext.getRealPath("/")
      def userDir = new File(webRootDir, "/upload")
      userDir.mkdirs()
      uploadedFile.transferTo(new File( userDir, uploadedFile.originalFilename))
      //println userDir
      
      println uploadedFile.originalFilename
      def fileName = userDir.toString() + "/" + uploadedFile.originalFilename.toString()
      
      
        ExcelImporter importer = new ExcelImporter(fileName)

	 def courseRuleList = importer.getCourseRuleList()
         
         def crList = []
         
       //计算课程学期
        // def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
         def currentTerm = params.entryTerm
         //Validation
         boolean flag = true
         for(Map courseRuleParams in courseRuleList)
         {
             def newCourseRule = new CourseRule(courseRuleParams)
             def ruleYear = newCourseRule.ruleYear as double
             newCourseRule.ruleYear = ruleYear.toInteger()
              newCourseRule.ruleTerm = ruleYear.toInteger().toString()+"年"+newCourseRule.ruleSeason.toString()
              
             
//              def _term = new Term("currentTerm":currentTerm,"entryTerm":newCourseRule.ruleTerm)
//              _term = Term.find(_term)
//              newCourseRule.courseTerm = _term?.courseTerm
              
            //计算学期号
             newCourseRule.courseTerm =  calcCourseTerm(currentTerm,newCourseRule.ruleTerm)
             println newCourseRule.ruleYear.class
             
            
          
              newCourseRule.currentTerm = currentTerm
              
             //TODO 
             if(newCourseRule.ruleYear == "2013.0")
             {
                flag = false
                flash.message = "上传失败, 适用入学年度列错误，请检查 （序号为"+ newCourseRule.ruleId.toString() + "行）"
                break
             }
             else
             {
                  crList.add(newCourseRule)
             }
          }
         //println crList

         if(flag)
         {
             //2012-07-16 不需要覆盖，直接把当学期的数据删除了重新导入 
             Course.executeUpdate("delete from CourseRule r " +
                      "where r.currentTerm='"+currentTerm+"'")
          
          
             crList.each {cr ->
                 if (!cr.save()) {
                  flash.message =  "CourseRule not saved, errors = ${cr.errors}"
                    }
                else
                    {
                  flash.message = message(code: 'default.upload.message', args: [message(code: 'courseRule.label', default: 'CourseRule')])
                    }
            }
          }
//            courseRuleList.each { Map courseRuleParams ->
//            def newCourseRule = new CourseRule(courseRuleParams)
//            if (!newCourseRule.save()) {
//                flash.message =  "CourseRule not saved, errors = ${newCourseRule.errors}"
//            }
//            else
//            {
//                flash.message = message(code: 'default.upload.message', args: [message(code: 'courseRule.label', default: 'CourseRule')])
//            }
           
         }
          redirect(action: "upload")
	 
    }
    
//计算学期
def calcCourseTerm(currentTerm,entryTerm)
    {
        def currentYear = currentTerm.getAt(0..3).toInteger()
        def entryYear = entryTerm.getAt(0..3).toInteger()
        def currentSeason = currentTerm.getAt(5..6)=="春季"?0:0.5
        def entrySeason = entryTerm.getAt(5..6)=="春季"?0:0.5
        def courseTerm =  (((currentYear+currentSeason) - (entryYear+entrySeason)+0.5)*2).toInteger()
        
          
//        //def entrySeason,entryTerm,entryYear
//        if(currentSeason==entrySeason)
//        {
//            courseTerm = (currentYear - entryYear)*2 + 1 
//        }
//        else
//        {
//            courseTerm = (currentYear - entryYear)*2
//        }
        if (courseTerm>6)
            courseTerm = ""
        return courseTerm
        
        
    }
    
       
 }

